package com.prime.nova.clipboardsharemonitor;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Locale;

//import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.prime.nova.clipboardsharemonitor.tools.Url2Name;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity {

	private ProgressDialog dialog;
	private String extraText;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		// Create progress dialog for later...
		

		// Get intent, action and MIME type
		Intent intent = getIntent();
		String action = intent.getAction();
		String type = intent.getType();

		// Got a send (should ONLY be for text!)
		if (Intent.ACTION_SEND.equals(action) && type != null) {
			extraText = intent.getStringExtra(Intent.EXTRA_TEXT);
			if (extraText != null) {
				String extraLower = extraText.toLowerCase(Locale.getDefault());
				
			    ClipboardManager clipboard = (ClipboardManager)
			            getSystemService(Context.CLIPBOARD_SERVICE);
			    
			    // Creates a new text clip to put on the clipboard
				ClipData clip = ClipData.newPlainText("Shared text", extraText);
				clipboard.setPrimaryClip(clip);
				
				
				Toast.makeText(this, "Text copied: " + extraText,
						Toast.LENGTH_LONG).show();
				
				if (extraLower.startsWith("http")) {
					if (extraLower.endsWith(".png") ||
							extraLower.endsWith(".jpg") ||
							extraLower.endsWith(".jpeg") ||
							extraLower.endsWith(".bmp")) {
					
						// Show a dialog.
						dialog = new ProgressDialog(this);
						dialog.setMessage("downloading stuff");
						dialog.setTitle("Downloading...");
						dialog.setMax(100);
						dialog.setIndeterminate(false);
						dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
						dialog.setProgress(0);

						// Start a kitten download.
						dlThread.start();
						
						
					} else {
						// Load browsable.
						Intent interTent = new Intent(Intent.ACTION_VIEW);
						interTent.setData(Uri.parse(extraText));
						startActivity(interTent);
						finish();
					}
				}
				
			}
		}
		else {
			Toast.makeText(this, "No share done.", Toast.LENGTH_LONG).show();
			finish();
		}

		//setContentView(R.layout.activity_main);

	}
	
	private Thread dlThread = new Thread(new Runnable() {
		
		@Override
		public void run() {
			HttpClient client = new DefaultHttpClient();
			HttpGet request = new HttpGet(extraText);	// use case-sensitive
			HttpResponse response;
			try {
				response = client.execute(request);
				
				// Get input stream from URL
				InputStream input = response.getEntity().getContent();

//				Header[] headers = response.getAllHeaders();
//				
//				for (Header header : headers) {
//					Log.i("header ", header.getName() + ":" + header.getValue());
//				}
				
				//get name
				final String filename = Url2Name.get(extraText);
				//get folder
				File dlFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
				// concatenate for full name
				File newFile = new File(dlFolder, filename);
				// get new stream
				FileOutputStream newFileStream = new FileOutputStream(newFile);

				long maxLength = response.getEntity().getContentLength();
				final int aReasonableSize = 1024*16;
				
				//Looper.prepare();
				runOnUiThread(new Runnable() {
					public void run() {
						dialog.setMessage("Downloading " + filename);
						dialog.show();
					}
				});
				
				try {
					long TotalBytes = 0;
					int curPercent = 0;
			        byte[] buffer = new byte[aReasonableSize];         
			        int bytesRead = 0;
			        while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
			        	newFileStream.write(buffer, 0, bytesRead);      
			        	TotalBytes += bytesRead;
			            
			            final int newPercent = (int)((float)TotalBytes/maxLength*100);
			            
			            // Only change if newPercent is.... new.
			            if (curPercent != newPercent) {
				            Log.i("bytesRead", String.valueOf(bytesRead));
				            Log.i("newPercent", String.valueOf(newPercent));
				            
			            	// update curpercent
			            	curPercent = newPercent;
				            
			            	// display it. Only "final" can be used, so use newPercent.
			            	runOnUiThread(new Runnable() {
								public void run() {
						            dialog.setProgress(newPercent);
								}
							});
			            }
			        }     
				} finally {
					newFileStream.close();
					runOnUiThread(new Runnable() {
						public void run() {
							dialog.dismiss();	
						}
					});
				}
				
				
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
			finally {
				finish();
			}
			finish();
		}
	});

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
//	private void sleep(int time) {
//		try {
//			Thread.sleep(time);
//		} catch (InterruptedException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//	}

}
